﻿using BarcodeDelay.bean;
using BarcodeDelay.FrameDecoder;
using BarcodeDelay.logHelp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class ChangeAddrHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListDepBarcodes = new ArrayList();

        private Hashtable htAutoSingProblem = new Hashtable();
        public event Action changeAddr;

        private Hashtable htTodayChange = new Hashtable();
       

        private static ChangeAddrHelperGen instance;
        public static ChangeAddrHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ChangeAddrHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string anayType)
        {
            try
            {
                initLog();
                m_arListDepBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListDepBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseChangeAddr));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }



        public void parseChangeAddr(object arListDepBarcodes)
        {
            StoParams.Instance.resMsg = "";
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {

                ArrayList arListTmpC = (ArrayList)arListDepBarcodes;
                logHelp.LogHelper.Instance.writeLog(" 开始改地址。。。个数 " + arListTmpC.Count.ToString());

                int totalQueryCount = 0;
                ArrayList arListBarcodes = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                bool isNewStart = false;
                string barcode = "";
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                DelayAnaHelperGen.Instance.m_arlist_Delayed_BarCodes.Clear();


                if (arListTmp.Count > 0)
                {
                    arListBarcodes.Add(arListTmp.Clone());
                    arListTmp.Clear();
                }
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;


                string httpRes = "";
                ArrayList arListAllGXTask = new ArrayList();
                foreach (ParcelBean parcelBean in (ArrayList)arListDepBarcodes)
                {
                    string strBarCode = parcelBean.wayBill;
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";


                    if (!UtilityHelp.Instance.resetToken(strBarCode, out pickName, out orderSource, out curSiteToken,out customerName))
                    {
                        /*if (curSiteToken == "")
                        {
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                            continue;
                        }

                        StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                        continue;*/
                        string lanshouSite = "";
                        if (curSiteToken == "")
                        {
                            FrameDecoderManager.Instance.htFailedParcel[strBarCode] = System.DateTime.Now;
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                            if(pickName!=""&&StoParams.Instance.isStrictMode)
                            {
                                if(StoParams.Instance.register_site!= pickName)
                                {
                                    StoParams.Instance.htResWechat[strBarCode] = "发件网点" + pickName + "  非我司单号  无法处理";
                                }
                            }

                            continue;

                        }

                        UtilityHelp.Instance.resetWechat(parcelBean, pickName);

                        ArrayList arListAllGXTask3 = new ArrayList();
                        string httpRes3 = "";
                        ArrayList arListRoadMap3 = JTDelayHelper.Instance.getRoadMap(strBarCode, out httpRes3, arListAllGXTask3);
                        lanshouSite = JTDelayHelper.Instance.getLanShouSite(arListRoadMap3);

                        string lanshouTime = JTDelayHelper.Instance.getLanShouTime(arListRoadMap3);
                        parcelBean.lanshouTime = lanshouTime;

                        if (lanshouSite != pickName && lanshouSite.Length > 2)
                        {
                            pickName = lanshouSite;
                        }
                        bool findSite = false;
                        foreach (DictionaryEntry de in StoParams.Instance.htDifferentSiteBarcodeInfo)
                        {
                            if (de.Key.ToString() == pickName)
                            {
                                findSite = true;
                                break;
                            }
                        }
                        if (!findSite)
                        {
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            if (pickName != "" && StoParams.Instance.isStrictMode)
                            {
                                if (StoParams.Instance.register_site != pickName)
                                {
                                    StoParams.Instance.htResWechat[strBarCode] = "发件网点" + pickName + "  非我司单号  无法处理";
                                }
                            }
                            continue;
                        }
                    }
                    parcelBean.lanshouSite = pickName;
                    if (parcelBean.taskType.Contains("自动"))
                    {
                        LogHelper.Instance.writeLog(parcelBean.taskType + " " + strBarCode);
                    }
                   
                    parcelBean.customerName = customerName;
                    arListAllGXTask = new ArrayList();

                    ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(strBarCode, out httpRes, arListAllGXTask);

                    if (arListRoadMap.Count == 0)
                    {
                        StoParams.Instance.interResMsg = httpRes;
                        if (httpRes.Contains("成功"))
                        {
                            StoParams.Instance.htResWechat[strBarCode] = "快件未发出无法改地址，后续跟踪";
                            parcelBean.replyType = "改地址无物流";

                            if (StoParams.Instance.register_site.Contains("沙溪") || StoParams.Instance.register_site.Contains("石岐南") || StoParams.Instance.register_site.Contains("沙朗隆平")
                            || StoParams.Instance.register_site.Contains("太和"))
                            {
                                parcelBean.replyType = "改地址无物流";
                                StoParams.Instance.htResWechat[strBarCode] = "暂无物流或未从转运中心发出，揽收后我司转寄";
                                continue;
                            }
                            if (StoParams.Instance.register_site.Contains("曹三") || StoParams.Instance.register_site.Contains("菊城"))
                            {
                                StoParams.Instance.htResWechat[strBarCode] = "快件未发出无法改地址，我司后台登记转出后修改";
                            }
                        }
                        else
                        {
                            StoParams.Instance.htResWechat[strBarCode] = httpRes;
                        }

                        continue;
                    }
                    string jisanSite = "";
                    string overTimeMention = UtilityHelp.Instance.getOverTimeParcel(arListRoadMap);
                    if (overTimeMention != "")
                    {
                        StoParams.Instance.htResWechat[parcelBean.wayBill] = overTimeMention;
                        continue;
                    }
                    if (!JTDelayHelper.Instance.canChageAddr(arListRoadMap, out jisanSite))
                    {
                        parcelBean.replyType = "改地址未出"+ jisanSite;
                        StoParams.Instance.htResWechat[strBarCode] = "快件未出"+ jisanSite + "暂时无法更改";
                        if (StoParams.Instance.register_site.Contains("后宅"))
                        {
                            parcelBean.replyType = "改地址未出" + jisanSite;
                            StoParams.Instance.htResWechat[strBarCode] = "快件未出金华暂时无法更改";
                            continue;
                        }
                        if (StoParams.Instance.register_site.Contains("和顺")|| StoParams.Instance.register_site.Contains("百安"))
                        {
                            parcelBean.replyType = "改地址未出" + jisanSite;
                            StoParams.Instance.htResWechat[strBarCode] = "快件未出集散暂时无法更改";
                            continue;
                        }
                        if (StoParams.Instance.register_site.Contains("东升"))
                        {
                            parcelBean.replyType = "改地址未出" + jisanSite;
                            StoParams.Instance.htResWechat[strBarCode] = "快件未出中山暂时无法更改";
                            continue;
                        }
                        if (StoParams.Instance.register_site.Contains("沙溪")|| StoParams.Instance.register_site.Contains("石岐南") || StoParams.Instance.register_site.Contains("沙朗隆平")
                            || StoParams.Instance.register_site.Contains("太和"))
                        {
                            parcelBean.replyType = "改地址未出" + jisanSite;
                            StoParams.Instance.htResWechat[strBarCode] = "暂无物流或未从转运中心发出，揽收后我司转寄";
                            continue;
                        }

                        if (StoParams.Instance.register_site.Contains("邓岗")|| StoParams.Instance.register_site.Contains("水洲"))
                        {
                            parcelBean.replyType = "改地址未出" + jisanSite;
                            StoParams.Instance.htResWechat[strBarCode] = "快件未出集散暂时无法更改";
                            continue;
                        }

                        if (StoParams.Instance.register_site.Contains("江门"))
                        {
                            parcelBean.replyType = "改地址未出" + jisanSite;
                            StoParams.Instance.htResWechat[strBarCode] = "快件未出中山暂时无法更改";
                            continue;
                        }
                        if (StoParams.Instance.register_site.Contains("阳江") || StoParams.Instance.register_site.Contains("阳东"))
                        {
                            if (!JTDelayHelper.Instance.isParcelLeaveFirstCenter(arListRoadMap, pickName))
                            {
                                parcelBean.replyType = "改地址未出集散或转运";
                                StoParams.Instance.htResWechat[strBarCode] = "快件未出" + "中山" + "暂时无法更改";
                                continue;
                            }
                        }

                        if (StoParams.Instance.register_site.Contains("禅"))
                        {
                            if (!JTDelayHelper.Instance.isParcelLeaveFirstCenter(arListRoadMap, pickName))
                            {
                                parcelBean.replyType = "改地址未出集散或转运";
                                StoParams.Instance.htResWechat[strBarCode] = "快件未出佛山禅南集散点，待发出后登记修改，跟进处理";
                                continue;
                            }
                        }

                        if (StoParams.Instance.register_site.Contains("凤岗"))
                        {
                            parcelBean.replyType = "改地址未出" + jisanSite;
                            if(parcelBean.phoneNumList.Count>0)
                            {
                                StoParams.Instance.htResWechat[strBarCode] = "此件已登记转寄,后续跟进转出新地址";
                            }
                            else
                            {
                                StoParams.Instance.htResWechat[strBarCode] = "改地址失败，改地址请携带电话号码";
                            }
                            
                            
                            continue;
                        }

                        if (StoParams.Instance.register_site.Contains("曹三") || StoParams.Instance.register_site.Contains("菊城"))
                        {
                            StoParams.Instance.htResWechat[strBarCode] = "我司后台登记包裹转出后修改";
                        }

                       continue;

                    }

                   

                    string siteName = "";
                    //JTDelayHelper.Instance.parseInterceptBarcode(arListRoadMap, out commentType, out strInterCeptSiteCode,out siteName);
                    string tmpLv = "";
                    string commentType = "";
                    string strInterCeptSiteCode = "";
                    JTDelayHelper.Instance.parseManualBarcode(arListRoadMap, out commentType, out strInterCeptSiteCode, out siteName, out tmpLv);
                    



                    if (JTDelayHelper.Instance.isLastRoadIsInterCeptReturn(arListRoadMap))
                    {
                        ArrayList arListTmpSend = new ArrayList();
                        arListTmpSend.Add(strBarCode);
                        CancelInterHelperGen.Instance.parseCancels(arListTmpSend);
                        StoParams.Instance.resMsg = "此件已拦截，先撤销拦截登记";
                        StoParams.Instance.htResWechat[strBarCode] = StoParams.Instance.resMsg;
                        System.Threading.Thread.Sleep(200);
                        if(changeAddr!=null)
                        {
                            changeAddr.Invoke();
                        }
                        


                    }
                    StoParams.Instance.resMsg = "";
                    intProcess++;
                    string strLeftTime = "10";

                    bool isReturnInRepley = false;
                    string outmsg = "";
                    JObject jObjDetail= JTDelayHelper.Instance.getWayBillDetail(strBarCode, out httpRes);
                    ArrayList arListDBOrJB = new ArrayList();
                    StoParams.Instance.curParces++;
                    if (!httpRes.Contains("成功"))
                    {
                        StoParams.Instance.resMsg = httpRes;
                        System.Threading.Thread.Sleep(500);
                        resMsg = httpRes;
                        
                        StoParams.Instance.htResWechat[strBarCode] = resMsg;
                        if(changeAddr!=null)
                        {
                            changeAddr.Invoke();
                        }
                        
                        continue;
                    }

                    string shortDateKey = System.DateTime.Now.ToShortDateString();
                    if (!htTodayChange.ContainsKey(shortDateKey))
                    {
                        htTodayChange[shortDateKey] = new Hashtable();
                    }
                    

                    string leaveMsg = "";
                    string outAddrMsg = "";
                    if(parcelBean.ori_addr.Contains("更："))
                    {
                        parcelBean.ori_addr = parcelBean.ori_addr.Substring(parcelBean.ori_addr.IndexOf("更：") + 3);
                    }

                    JObject jObAddr = JTDelayHelper.Instance.getInfoByAddr(parcelBean.ori_addr, out outAddrMsg);

                    string person = jObAddr["person"].ToString();
                    if(person=="")
                    {
                        parcelBean.ori_addr = UtilityHelp.Instance.getNameFirstAddr(parcelBean.ori_addr);
                        jObAddr = JTDelayHelper.Instance.getInfoByAddr(parcelBean.ori_addr, out outAddrMsg);
                    }
                    person = jObAddr["person"].ToString();
                    if(person=="")
                    {
                        if (parcelBean.ori_addr.Length>3)
                        {
                            person = parcelBean.ori_addr.Substring(0, 3);
                            jObAddr["person"] = person;
                        }
                        
                    }

                    if (!outAddrMsg.Contains("成功")|| !httpRes.Contains("成功"))
                    {
                        StoParams.Instance.htResWechat[strBarCode] = resMsg;
                        if(changeAddr!=null)
                        {
                            changeAddr.Invoke();
                        }
                        
                        return;
                    }
                    string provinceCode = jObAddr["provinceCode"].ToString();
                    string cityCode = jObAddr["cityCode"].ToString();
                    string countyCode = jObAddr["countyCode"].ToString();
                   

                    string townName = jObAddr["town"].ToString();
                    string strMsg = "";
                    JObject jObjProvince = JTDelayHelper.Instance.getProvince(provinceCode, strMsg);
                    JObject jObjCity = JTDelayHelper.Instance.getCity(provinceCode, cityCode, strMsg);
                    JObject jObjTown = JTDelayHelper.Instance.getArea(cityCode, countyCode, strMsg, townName);

                    if (jObAddr["county"] != null && jObAddr["county"].ToString() == "")
                    {
                        jObAddr["county"] = townName;
                    }

                    jObjDetail["newReceiverProvince"] = jObjProvince;
                    jObjDetail["newReceiverCity"] = jObjCity;
                    jObjDetail["newReceiverArea"] = jObjTown;

                    jObjDetail["newPackageChargeWeight"] = jObjDetail["packageChargeWeight"];
                    jObjDetail["newSettlementId"] = jObjDetail["settlementId"];
                    jObjDetail["newSettlementCode"] = jObjDetail["settlementCode"];
                    jObjDetail["newSettlementName"] = jObjDetail["settlementName"];
                    jObjDetail["newSenderProvinceId"] = jObjDetail["senderProvinceId"];
                    jObjDetail["newSenderProvinceName"] = jObjDetail["senderProvinceName"];
                    jObjDetail["newSenderCityId"] = jObjDetail["senderCityId"];
                    jObjDetail["newSenderCityName"] = jObjDetail["senderCityName"];
                    jObjDetail["newSenderAreaId"] = jObjDetail["senderAreaId"];
                    jObjDetail["newSenderAreaName"] = jObjDetail["senderAreaName"];
                    jObjDetail["newSenderName"] = jObjDetail["senderName"];
                    jObjDetail["newSenderMobilePhone"] = jObjDetail["senderMobilePhone"];

                    jObjDetail["newSenderTelphone"] = jObjDetail["senderTelphone"];
                    jObjDetail["newSenderTownship"] = jObjDetail["senderTownship"];
                    jObjDetail["newSenderStreet"] = jObjDetail["senderStreet"];
                    jObjDetail["newSenderDetailedAddress"] = jObjDetail["senderDetailedAddress"];

                    jObjDetail["newReceiverName"] = jObAddr["person"];

                    string partNumber = "";
                    if (parcelBean.phoneNumList.Count == 0)
                    {
                        List<string> phoneList = UtilityHelp.Instance.GetTelephoneList(parcelBean.ori_addr, parcelBean.wayBill);
                        foreach (string phone in phoneList)
                        {
                            parcelBean.phoneNumList.Add(phone);
                        }
                    }
                    if (parcelBean.phoneNumList.Count>0)
                    {
                        string phone = parcelBean.phoneNumList[parcelBean.phoneNumList.Count-1];
                        if(phone.Contains("-"))
                        {
                            partNumber = phone.Substring(phone.IndexOf('-') + 1);
                            phone = phone.Substring(0, phone.IndexOf('-'));
                            
                        }
                        if(phone.Contains(jObAddr["phonenum"].ToString()))
                        {
                            jObAddr["phonenum"] = phone;
                        }
                    }
                    

                    jObjDetail["newReceiverMobilePhone"] = jObAddr["phonenum"];
                    jObjDetail["newReceiverMobilePhone2"] = null;
                    jObjDetail["newReceiverTelphone"] = null;
                    jObjDetail["newReceiverTelphone2"] = null;

                    jObjDetail["applyTypeCode"] = 5;

                    if(partNumber!="")
                    {
                        if(!parcelBean.ori_addr.Contains("分机")&& !parcelBean.ori_addr.Contains("["))
                        {
                            partNumber = "[" + partNumber + "]";
                        }
                    }
                    if(jObAddr["town"]!=null)
                    {
                        string tmpDetail = jObAddr["town"].ToString() + jObAddr["detail"].ToString();
                        if(!parcelBean.ori_addr.Contains(tmpDetail)|| tmpDetail.Length<2)
                        {
                            if(parcelBean.ori_addr.Contains(jObAddr["county"].ToString())&& jObAddr["county"].ToString().Length>1)
                            {
                                tmpDetail = parcelBean.ori_addr.Substring(parcelBean.ori_addr.IndexOf(jObAddr["county"].ToString()));
                                
                            }
                            else
                            {
                                if (parcelBean.ori_addr.Contains(jObAddr["city"].ToString())&& jObAddr["city"].ToString().Length>1)
                                {
                                    tmpDetail = parcelBean.ori_addr.Substring(parcelBean.ori_addr.IndexOf(jObAddr["city"].ToString()));
                                }
                            }
                            if(partNumber.Contains("["))
                            {
                                tmpDetail = tmpDetail + " " + partNumber;
                            }
                            jObjDetail["newReceiverDetailedAddress"] = tmpDetail;
                        }
                        else
                        {
                            if (partNumber.Contains("["))
                            {
                                jObAddr["detail"] = jObAddr["detail"].ToString() + " " + partNumber;
                            }
                            jObjDetail["newReceiverDetailedAddress"] = jObAddr["town"].ToString() + jObAddr["detail"].ToString();
                        }
                        
                    }
                    else
                    {
                        if (partNumber.Contains("["))
                        {
                            jObAddr["detail"] = jObAddr["detail"].ToString() + " " + partNumber;
                        }
                        jObjDetail["newReceiverDetailedAddress"] =jObAddr["detail"].ToString();
                    }
                    
                    jObjDetail["rebackTransferReason"] = "改地址 "+jObAddr["context"];
                    jObjDetail["newReceiverProvinceName"] = jObAddr["province"];
                    jObjDetail["newReceiverCityName"] = jObAddr["city"];
                    jObjDetail["newReceiverAreaName"] = jObAddr["county"];
                    jObjDetail["newReceiverProvinceId"] = jObAddr["provinceCode"];
                    jObjDetail["newReceiverCityId"] = jObAddr["cityCode"];
                    jObjDetail["newReceiverAreaId"] = jObAddr["countyCode"];
                    jObjDetail["countryId"] = 1;

                    string strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/add";

                    if (StoParams.Instance.isRabbitWin)
                    {
                        strUrl = "https://wdgw.jtexpress.com.cn/ops/wdbutler/rebackTransferExpress/add";
                    }

                    bool hasSingedProblem = false;
                    string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObjDetail);
                    string res = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "returnAndForwardMaintainAddSite");
                    if (!res.Contains("请求成功"))
                    {
                        if (res.Contains("msg"))
                        {
                            JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                            JToken msgToken = jsonObjRes["msg"];
                            res = msgToken.ToString();
                        }


                        if(res.Contains("失败")&&parcelBean.taskType.Contains("自动"))
                        {
                            continue;
                        }
               
  
                        StoParams.Instance.curFailedBarcode = strBarCode;
                        StoParams.Instance.resMsg = " 更改地址失败 "+ res;
                        if(res.Contains("审核"))
                        {
                            StoParams.Instance.resMsg =   "系统中存在待审核";
                        }
                        string errorMsg = "";
                        string leaveMsgType = "改地址";
                        bool isYishi = false;
                        string fullMsg = "";
                        
                        /*if(commentType.Contains("签收"))
                        {
                            isYishi = true;
                            leaveMsgType = "签收";
                        }*/
                        if (!parcelBean.isYishi)
                        {
                            UtilityHelp.Instance.parseIsYishi(parcelBean, arListRoadMap);
                        }
                        
                        if(StoParams.Instance.register_site.Contains("永平"))
                        {
                            parcelBean.isYishi = true;
                        }
                        

                        string phoneNumber = "";
                        if (parcelBean.phoneNumList.Count > 0)
                        {
                            phoneNumber = parcelBean.phoneNumList[parcelBean.phoneNumList.Count-1];
                        }

                        if (parcelBean.taskType.Contains("自动")&& parcelBean.wayBill.Length>10)
                        {
                            if (htTodayChange.ContainsKey(shortDateKey))
                            {
                                Hashtable htToday = htTodayChange[shortDateKey] as Hashtable;
                                if (!htToday.ContainsKey(parcelBean.wayBill))
                                {
                                    htToday[parcelBean.wayBill] = 1;
                                }
                                else
                                {
                                    int oriCpint = Convert.ToInt32(htToday[parcelBean.wayBill].ToString());
                                    if (oriCpint < 4)
                                    {
                                        oriCpint++;
                                        htToday[parcelBean.wayBill] = oriCpint;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                            }
                        }

                        if (LeaveMessageHelperGen.Instance.addComment(phoneNumber,strBarCode, leaveMsgType, parcelBean.ori_addr, "", parcelBean.wechat,out errorMsg,out fullMsg, isYishi))
                        {
                            if(res.Contains("入库"))
                            {
                                StoParams.Instance.resMsg =  "此件已派送或者签收，可能无法转寄。";
                                //if((StoParams.Instance.register_site.Contains("后宅")|| StoParams.Instance.register_site.Contains("阳江")) && !commentType.Contains("签收"))
                                {
                                    string outMsg = "";
                                    hasSingedProblem=signProblemParcel(strBarCode, out outMsg, strInterCeptSiteCode, siteName, parcelBean.ori_addr);
                                    StoParams.Instance.resMsg = "快件已出仓派送，系统不允许直接登记转寄申请，已留言通知更改地址，需要原收件人配合拒收哦。";
                                }
                            }
                            else
                            {
                                StoParams.Instance.resMsg =  " 更改地址失败 " + res + " 已留言尝试退转";
                                if(StoParams.Instance.resMsg.Contains("已签收"))
                                {
                                    StoParams.Instance.resMsg = " 以上单号已签收，无法申请！ 已留言尝试退转";
                                }
                            }
                            
                        }
                        else
                        {
                            StoParams.Instance.resMsg = " 更改地址失败 " + res + " 留言退转失败："+ errorMsg;
                        }
                    }
                    else
                    {
                        bool canAddMsg = false;
                        if(siteName.Contains("网点")&&siteName!=StoParams.Instance.register_site)
                        {
                            canAddMsg = true;
                            string outMsg = "";
                            if(!res.Contains("运单不存在")&&!hasSingedProblem)
                            {
                                hasSingedProblem = signProblemParcel(strBarCode, out outMsg, strInterCeptSiteCode, siteName, parcelBean.ori_addr);
                            }
                            
                        }
                        StoParams.Instance.currentBarcode = strBarCode;
                        StoParams.Instance.resMsg =  " 此件已登记转寄,后续跟进转出新地址";


                        if(StoParams.Instance.register_site.Contains("太和"))
                        {
                            //StoParams.Instance.resMsg = "已登记 新地址为：" + parcelBean.addr;
                        }

                        if(StoParams.Instance.isChangeSuccessLeaveMsg|| canAddMsg)
                        {
                            string leaveMsgType = "改地址";
                            string phoneNumber = "";
                            string errorMsg = "";
                            string fullMsg = "";
                            bool isYishi = false;
                            if (parcelBean.phoneNumList.Count > 0)
                            {
                                phoneNumber = parcelBean.phoneNumList[parcelBean.phoneNumList.Count - 1];
                            }

                            string priorMsg=StoParams.Instance.resMsg;
                            LeaveMessageHelperGen.Instance.addComment(phoneNumber, strBarCode, leaveMsgType, parcelBean.ori_addr, "", parcelBean.wechat, out errorMsg, out fullMsg, isYishi);
                            StoParams.Instance.resMsg = priorMsg;
                        }
                    }
                    if (siteName.Contains("网点") && siteName != StoParams.Instance.register_site)
                    {
                        string outMsg = "";
                        if (!hasSingedProblem)
                        {
                            hasSingedProblem = signProblemParcel(strBarCode, out outMsg, strInterCeptSiteCode, siteName, parcelBean.ori_addr);
                        }
                    }

                    resMsg = StoParams.Instance.resMsg;

                    if(resMsg.Contains("请勿重复申请"))
                    {
                        if (StoParams.Instance.register_site.Contains("无锡锡山区东亭网点") || StoParams.Instance.register_site.Contains("无锡锡山区查桥网点"))
                        {
                            resMsg = "已登记改址";
                        }
                    }

                    if(resMsg.Contains("此件已登记转寄"))
                    {
                        if(StoParams.Instance.register_site.Contains("永平")|| (StoParams.Instance.register_site.Contains("均禾")))
                        {
                            string lastStauts = UtilityHelp.Instance.getLastValidStatus(arListRoadMap);
                            if(lastStauts.Contains("派件"))
                            {
                                resMsg = "已派件，此件已登记转寄,后续跟进转出新地址";
                            }
                            else if (lastStauts.Contains("第三方"))
                            {
                                resMsg = "已入库，此件已登记转寄,后续跟进转出新地址";
                            }
                        }
                        FrameDecoderManager.Instance.htTaskCheck[parcelBean] = System.DateTime.Now;
                    }
                    if(!StoParams.Instance.htResWechat.ContainsKey(strBarCode))
                    {
                        StoParams.Instance.htResWechat[strBarCode] = resMsg;

                    }
                    else
                    {
                        StoParams.Instance.htResWechat[strBarCode] = StoParams.Instance.htResWechat[strBarCode].ToString() + "\r\n" + resMsg.Replace(strBarCode,"");
                    }


                    if(StoParams.Instance.htResWechat[strBarCode].ToString().Contains("请勿重复申请"))
                    {
                        StoParams.Instance.htResWechat[strBarCode] = "系统中存在待审核/已审核的申请记录，请勿重复申请哦";
                    }

                    if (StoParams.Instance.htResWechat[strBarCode].ToString().Contains("运单已签收"))
                    {
                        StoParams.Instance.htResWechat[strBarCode] = "以上单号已签收，无法申请修改，已留言尝试退转哦";
                    }
                    if (StoParams.Instance.htResWechat[strBarCode].ToString().Contains("后续跟进转出新地址"))
                    {
                        if (StoParams.Instance.register_site.Contains("曹三") || StoParams.Instance.register_site.Contains("菊城"))
                        {
                            StoParams.Instance.htResWechat[strBarCode] = "以上单号已登记修改";
                        }
                    }
                        


                    if (changeAddr!=null)
                    {
                        changeAddr.Invoke();
                    }
                    
                    Random ran = new Random();


                    Thread.Sleep(200);
                    StoParams.Instance.currentBarcode = strBarCode.Trim();


                }



            }
            catch (Exception ex)
            {
                

            }
            int tiot = queryServerResTime;
           


        }

     
        private bool signProblemParcel(string strCurBarcode, out string msg, string strInterCeptSiteCode, string siteName,string addr)
        {


            msg = "";
            bool res = false;
            try
            {
                string strQueryUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/queryOperationType?waybillNo=" + strCurBarcode;
                JObject jObj = new JObject();
                JArray jarry = new JArray();

                /*string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strQueryUrl, postData, "GET", "batchProblem");
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "登记失败";
                    return false;
                }

                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JArray records = (JArray)jsonObjRes["data"];
                if (records.Count == 0)
                {
                    msg = "登记失败";
                    return false;
                }
                string codeStr = "";
                for (int i = 0; i < records.Count; i++)
                {
                    JObject jsonObjFirst = (JObject)records[0];
                    JToken codeToken = jsonObjFirst["code"];
                    codeStr = codeToken.ToString();
                    if (codeStr == "4")
                    {
                        break;
                    }
                }
                codeStr = "1";
                strQueryUrl = "https://jmsgw.jtexpress.com.cn/basicdata/sysAbnormalPiece/select?size=999999&levelType=1&operatorType=" + codeStr;
                jObj = new JObject();
                jarry = new JArray();

                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strQueryUrl, postData, "GET", "batchProblem");
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "登记失败";
                    return false;
                }

                jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject dataObj = (JObject)jsonObjRes["data"];
                records = (JArray)dataObj["records"];
                if (records.Count == 0)
                {
                    msg = "登记失败";
                    return false;
                }*/
     



                //string strUrl = "https://jmsgw.jtexpress.com.cn/basicdata/network/select/all?current=1&size=100&name=" + strInterCeptSiteCode + "&typeIds%5B0%5D=336&queryLevel=3";
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/getPageByName?current=1&size=10&queryLevel=3&name=" + siteName;
                if (StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/servicequality/problemPiece/getPageByName?current=1&size=10&queryLevel=3&name=" + siteName;
                }
                jObj = new JObject();
                jarry = new JArray();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "batchProblem");
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "登记失败";
                    return false;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject jsonObjData = (JObject)jsonObjRes["data"];
                JArray records = (JArray)jsonObjData["records"];
                if (records.Count == 0)
                {
                    msg = "网点编码：" + strInterCeptSiteCode + " 不存在,跳过登记环节";
                    return false;
                }
                string signStieCode = "";
                int receiveNetworkId = 0;
                for (int i = 0; i < records.Count; i++)
                {
                    JObject json = (JObject)records[i];
                    JToken code = json["code"];
                    JToken id = json["id"];
                    if (code != null)
                    {
                        if (code.ToString() == strInterCeptSiteCode || id.ToString() == strInterCeptSiteCode)
                        {
                            signStieCode = code.ToString();
                            if (id != null)
                            {
                                receiveNetworkId = Convert.ToInt32(id);
                            }
                            break;
                        }
                    }
                }
                if (signStieCode == "" || receiveNetworkId == 0)
                {
                    msg = "网点编码：" + strInterCeptSiteCode + " 不存在,跳过登记环节";
                    return false;
                }


                string firstLevelTypeName = "催件";
                int probleTypeSubjectId = 100123;
                int probleTypeSubjectId2 = 100124;
                string problemTypeSubjectCode = "50";
                string secondLevelTypeCode = "50a";
                int secondLevelTypeId = 100124;
                string secondLevelTypeName = "催件a";

          

                bool resSign = signType(out msg, secondLevelTypeName, probleTypeSubjectId, probleTypeSubjectId2,
                                        problemTypeSubjectCode, secondLevelTypeCode, secondLevelTypeId, receiveNetworkId, strCurBarcode, addr);
                if (resSign)
                {
                    return true;
                }
                /*else
                {
                    firstLevelTypeName = "客户拒收";
                    probleTypeSubjectId = 108;
                    probleTypeSubjectId2 = 100136;
                    problemTypeSubjectCode = "16";
                    secondLevelTypeCode = "16b";
                    secondLevelTypeId = 100136;
                    secondLevelTypeName = "未开箱无理由拒收";
                    resSign = signType(out msg, secondLevelTypeName, probleTypeSubjectId, probleTypeSubjectId2,
                                        problemTypeSubjectCode, secondLevelTypeCode, secondLevelTypeId, receiveNetworkId, strCurBarcode);
                }*/
                return resSign;


                /*if (StoParams.Instance.probleTypeSubject != "return")
                {

                    firstLevelTypeName = "客户拒收";
                    probleTypeSubjectId = 108;
                    probleTypeSubjectId2 = 100136;
                    problemTypeSubjectCode = "16";
                    secondLevelTypeCode = "16b";
                    secondLevelTypeId = 100136;
                    secondLevelTypeName = "未开箱无理由拒收";
                }

                strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/registration";
                string routerName = "batchProblem";
                jObj = new JObject();
                jObj["countryId"] = "1";
                jObj["defaultKnow"] = null;
                jObj["firstLevelTypeName"] = secondLevelTypeName;
                jObj["knowNetwork"] = "";
                jObj["paths"] = "";
                jObj["probleTypeId"] = 1;
                jObj["probleTypeSubjectId"] = probleTypeSubjectId;
                jObj["probleTypeSubjectId2"] = probleTypeSubjectId2;
                jObj["problemPieceId"] = "";
                jObj["problemTypeSubjectCode"] = problemTypeSubjectCode;
                jObj["receiveNetworkId"] = receiveNetworkId;
                jObj["replyContent"] = "";
                jObj["probleDescription"] = "此件麻烦尽快退回，客户已拒收，商家急催，避免客户投诉，如已遗失，麻烦联系我司处理理赔 ";
                jObj["replyContentImg"] = new JArray();
                jObj["replyStatus"] = 0;
                jObj["secondLevelTypeCode"] = secondLevelTypeCode;
                jObj["secondLevelTypeId"] = probleTypeSubjectId2;
                jObj["secondLevelTypeName"] = secondLevelTypeName;
                jObj["uploadDataProp"] = "";
                jObj["waybillNo"] = strCurBarcode;
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

                resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, routerName);
                if (!resMsg.Contains("请求成功"))
                {
                    jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];

                    msg = "登记失败:"+ msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "登记成功";
                    return true;
                }*/

            }
            catch (Exception ex)
            {

            }



            return res;
        }

        private bool signType(out string msg, string secondLevelTypeName, int probleTypeSubjectId, int probleTypeSubjectId2,
                                        string problemTypeSubjectCode, string secondLevelTypeCode, int secondLevelTypeId,
                                        int receiveNetworkId, string strCurBarcode,string addr)
        {
            addr = "此件客户未收到要求改地址转出，" + addr;
            if (addr.Length>100)
            {
                addr = addr.Substring(0, 100);
            }
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/registration";
                if (StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/servicequality/problemPiece/registration";
                }
                string routerName = "batchProblem";
                JObject jObj = new JObject();
                jObj["countryId"] = "1";
                jObj["defaultKnow"] = null;
                jObj["firstLevelTypeName"] = secondLevelTypeName;
                jObj["knowNetwork"] = "";
                jObj["paths"] = "";
                jObj["probleTypeId"] = 1;
                jObj["probleTypeSubjectId"] = probleTypeSubjectId;
                jObj["probleTypeSubjectId2"] = probleTypeSubjectId2;
                jObj["problemPieceId"] = "";
                jObj["problemTypeSubjectCode"] = problemTypeSubjectCode;
                jObj["receiveNetworkId"] = receiveNetworkId;
                jObj["replyContent"] = "";
                jObj["probleDescription"] = addr;
                jObj["replyContentImg"] = new JArray();
                jObj["replyStatus"] = 0;
                jObj["secondLevelTypeCode"] = secondLevelTypeCode;
                jObj["secondLevelTypeId"] = probleTypeSubjectId2;
                jObj["secondLevelTypeName"] = secondLevelTypeName;
                jObj["uploadDataProp"] = "";
                jObj["waybillNo"] = strCurBarcode;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

                string resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, routerName);
                if (!resMsg.Contains("请求成功"))
                {
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];

                    msg = "登记失败:" + msgToke.ToString();
                    return false;
                }
                else
                {
                    res = true;
                    msg = "登记成功";
                    return true;
                }
            }
            catch (Exception ex)
            {

            }
            return res;
        }







        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
